package log

import (
	"context"
	"github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap"
	"github.com/pkg/errors"
	"github.com/spf13/viper"
	"go.uber.org/zap"
)

type Logger interface {
	Debug(args ...interface{})
	Debugf(template string, args ...interface{})
	Info(args ...interface{})
	Infof(template string, args ...interface{})
	Warn(args ...interface{})
	Warnf(template string, args ...interface{})
	Error(args ...interface{})
	Errorf(template string, args ...interface{})
}


type CtxLogger func(context.Context) Logger

// New zap logger
func NewZapLogger(v *viper.Viper) (*zap.Logger, func()) {
	var (
		logger *zap.Logger
		err    error
	)
	if v.GetString("env") == "dev" {
		logger, err = zap.NewDevelopment()
	} else {
		logger, err = zap.NewProduction()
	}

	if err != nil {
		panic(errors.Wrap(err, "New zap logger failed."))
	}

	return logger, func() { logger.Sync() }
}

func NewLogger(zl *zap.Logger) Logger {
	return zl.Sugar()
}

// Extract zap.Logger from context and use its SugaredLogger
func NewCtxLogger() CtxLogger {
	return func(ctx context.Context) Logger {
		return ctxzap.Extract(ctx).Sugar()
	}
}
